package com.service.zy;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.zy.ProductDao;
import com.dao.zy.ProductMybatisDao;
import com.dao.zy.ProductStandardDao;
import com.dao.zy.ProductStandardMybatisDao;
import com.entity.Product;
import com.entity.ProductStandard;
import com.service.ServiceException;

@Service
@Transactional(rollbackFor=ServiceException.class)
public class ProductService {
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ProductStandardDao productstandardDao;
	@Autowired
	private ProductMybatisDao productmybatisDao;
	@Autowired
	private ProductStandardMybatisDao productstandardmybatisDao;
	
	/**
	 * 添加一个产品
	 * @param pro
	 */
	public void addProduct(Product pro) throws ServiceException {
		try {
			productDao.save(pro);
			//添加一个产品的同时添加一个基准规格
			ProductStandard ps = new ProductStandard();
			ps.setProduct(pro);
			ps.setName("基准");
			ps.setUnitId(pro.getUnitId());
			ps.setPrice(pro.getPrice());
			ps.setStatus(pro.getStatus());
			ps.setCode(pro.getCode());
			productstandardDao.save(ps);
		}catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	/**
	 * 删除一个产品
	 * @param id
	 * @throws ServiceException
	 */
	public void delProduct(Long id) throws ServiceException {
		try {
			//产品下无其他规格时才可删除
			if(productstandardmybatisDao.queryByProId(id).size()<1) {
				productDao.delete(id);
			}else {
				System.out.println("存在子规格不可删除");
			}
		}catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	/**
	 * 通过产品id查询产品
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	public Product findOne(Long id) throws ServiceException {
		try {
			Product pro = productDao.findOne(id);
			return pro;
		}catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	/**
	 * 查询所有产品
	 * @return
	 */
	public List<Product> findAll(){
		return (List<Product>) productDao.findAll();
	}
	/**
	 * 按类别查询产品
	 * @param classId
	 * @return
	 */
	public List<Product> findByClassify(Long classId){
		return productmybatisDao.findbyClassify(classId);
	}
	/**
	 * 根据是否计算库存查询产品
	 * @return
	 */
	public List<Product> findByIsstock(boolean isStock){
		return productmybatisDao.findbyIsstock(isStock);
	}
}
